package juc.work;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 有四个任务abcd   bcd等a执行完立刻执行
 *
 */
public class TaskArrange {
    public class Task implements Runnable {
        private String taskName;

        public Task(String name) {
            this.taskName = name;
        }

        @Override
        public void run() {
            System.out.println("执行任务:" +taskName);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("任务执行完毕:" +taskName);
        }
    }

    /**
     * ExecutorService和CompletableFuture实现
     */
    public void taskArrange() {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        // 任务编排
        CompletableFuture<Void> taska = CompletableFuture.runAsync(new Task("a"), executorService);
        CompletableFuture<Void> taskb = taska.thenRunAsync(new Task("b"), executorService);
        CompletableFuture<Void> taskc = taska.thenRunAsync(new Task("c"), executorService);
        CompletableFuture<Void> taskd = taska.thenRunAsync(new Task("d"), executorService);
        // 任务启动
        CompletableFuture.allOf(taskb, taskc, taskd).join();
        executorService.shutdown();
    }

    /**
     * CountDownLatch实现
     */
    public void taskArrange2() {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CountDownLatch countDownLatchA = new CountDownLatch(1);
        CountDownLatch countDownLatchBCD = new CountDownLatch(3);
        executorService.execute(new Task("a"));


    }


    public static void main(String[] args) {
        TaskArrange taskArrange = new TaskArrange();
        taskArrange.taskArrange();
    }
}
